import React,{useState,useEffect} from 'react';
import { Card,Table,Tooltip,message ,Button,Divider} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {HasPermission} from '@/components/AuthComponent/HasPermission';
import db from '@/utils/localstorage';
import { connect,history } from 'umi';
import Resevation from '../save'
import { saveMemberSigned,saveBookingCourse,cancelSign } from '../service';
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);
const AuthPlus = HasPermission(PlusOutlined);
const YyRecord = props =>{
    const {submitting,classTableInfo,dispatch,membersList,member,membersCardList,coachList,shopList,memberBookInfoList,timeList,siteList} = props;
    const [visible, setVisible] = useState(false);
    const [venueId, setVenueId] = useState("");
    const [venueName, setVenueName] = useState("");
    const [classId, setClassId] = useState("");
    const [type, setType] = useState("");
    const [classIdSign, setClassIdSign] = useState("");
    useEffect(() => {
        if (dispatch) {
          dispatch({
            type: 'cubeReservationRecord/fetchCoach',
            payload: {
              empType:2,
            },
          })
          dispatch({
            type: 'cubeReservationRecord/fetchShopList',
            payload:{
              userId:db.get("user").userId
            }
          })
         }
       }, []);
    const columns =[
        {
            title: '姓名',
            dataIndex: 'memberName',
            render:(text,record)=><a onClick={()=>goVipDetail(record)}>{text}</a>
        },
        {
            title: '电话',
            dataIndex: 'memberPhone',
        },
        {
            title: '人数',
            dataIndex: 'bookingNum',
        },
        {
            title: '会员卡',
            dataIndex: 'cardName',
        },
        {
          title: '场地',
          dataIndex: 'siteName',
      },
        {
            title: '状态',
            dataIndex: 'status',
            render: (text, record) => {
                let bookingCourseType = db.get("dictTypeList")["booking_course_type"]
                let _status = bookingCourseType.filter((item)=>item.value == text )
                if(_status&&_status.length>0){
                 return _status[0].label
                }
               }
        },
        {
            title: '备注',
            dataIndex: 'zb',
        },
        {
            title: '预约时间',
            dataIndex: 'appointmentTime',
        },
        {
            title: '操作',
            dataIndex: 'action',
            render: (text, record) => (
                <>
               {
                 (record.status =='1'||record.status =='2')? <AuthButton auth={[`sign:reservation:sign`]} type="link"  onClick={() => sign(record)}>签到</AuthButton>:""
               }
               {
                 (record.status =='1'||record.status =='2')?<AuthDivider auth={['sign:reservation:sign','sign:reservation:reservation:no']} type="vertical"></AuthDivider>:""
               }
                {
                  (record.status =='1'||record.status =='2'||record.status =='6')&&<AuthButton auth={[`sign:reservation:reservation:no`]} type="link"  onClick={() => _cancelSign(record)}>取消预约</AuthButton>
                }
                </>
              ),
        },
    ]

    /**
     * 跳转会员详情
     * @param {*} record 
     */
    const goVipDetail = (record) =>{
        history.push(`/vip/center/detail/${record.memberId}`);
    }
/**
   * 取消预约
   * @param {*} record 
   */
 const _cancelSign = async record  =>{
    const hide = message.loading('正在取消预约');
    let params={
      id:record.bookingCourseId,
      status:record.status
    }
    try {
      let result = await cancelSign({ ...params });
      hide();
      if(result.code==0){
        message.success('取消成功');
        dispatch({
          type: 'cubeReservationRecord/queryMemberBookingCourseInfoByClassId',
          payload: {
            classId:classTableInfo.id
          },
        });
        dispatch({
            type: 'cubeReservationRecord/queryClassTableInfoById',
            payload: {
              classId:classTableInfo.id
            },
          });
        return true;
      }else{
        message.success(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('取消失败，请重试！');
      return false;
    }
   }
  
    /**
     * 签到
     */
    const sign = async record =>{
      const hide = message.loading('正在签到');
      let params={}
      params.cardId=record.cardId
      params.cost=record.bookingNum
      params.memberId=record.memberId
      params.bookingCourseId=[record.bookingCourseId]
      params.zb='预约点击签到'
      try {
        let result = await saveMemberSigned({ ...params });
        hide();
        if(result.code==0){
          message.success('签到成功');
          dispatch({
            type: 'cubeReservationRecord/queryMemberBookingCourseInfoByClassId',
            payload: {
              classId:classTableInfo.id
            },
          });
          dispatch({
            type: 'cubeReservationRecord/queryClassTableInfoById',
            payload: {
              classId:classTableInfo.id
            },
          });
          return true;
        }else{
          message.success(result.message);
          return false;
        }
      } catch (error) {
        hide();
        message.error('签到失败，请重试！');
        return false;
      }
    }

    const showModal = () => {
        setVisible(true)
      };
   //去预约
    const gotoYuyue = (venueId,classId,type,venueName) =>{
        setVenueId(venueId)
        setVenueName(venueName)
        setClassId(classId)
        setType(type)
        if(type=='3'){
          dispatch({
            type: 'cubeReservationRecord/fetchTimeList',
            payload: {
              classId:classId
            },
          })
          dispatch({
            type: 'cubeReservationRecord/querySiteInfoListByVenueIdNotPage',
            payload: {
              id:venueId
            },
          })
          showModal()
        }else{
          showModal()
        }
    }

    const hideModal = () => {
        setVisible(false)
        setVenueId("")
        setVenueName("")
        setClassId("")
        setType("")
        setClassIdSign("")
        dispatch({
          type: 'cubeReservationRecord/common',
          payload: {
            membersList:[],
            member:null
          },
        });
      };
    
  //添加预约
  const onFinish = async (values,callback) =>{
    const hide = message.loading('正在添加');
    values.classId=classId
    values.memberId=member.id
    try {
      let result = await saveBookingCourse({ ...values });
      hide();
      if(result.code==0){
        hideModal();
        message.success('添加成功，立即刷新');
        dispatch({
            type: 'cubeReservationRecord/queryMemberBookingCourseInfoByClassId',
            payload: {
              classId:classTableInfo.id
            },
          });
          dispatch({
            type: 'cubeReservationRecord/queryClassTableInfoById',
            payload: {
              classId:classTableInfo.id
            },
          });
        return true;
      }else{
        message.success(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('添加失败，请重试！');
      return false;
    }
  }

   //会员查询
  const handleSearch = (value) =>{
    if(value){
      let timeout;
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      function fake() {
        dispatch({
          type: 'cubeReservationRecord/fetchMembersList',
          payload: {
            text:value
          },
        })
      }
      timeout = setTimeout(fake, 500);
    }else{
      dispatch({
        type: 'cubeReservationRecord/common',
        payload: {
          membersList:[]
        },
      });
    }
  }

  //选择会员
  const handleSelect = value =>{
      //检索会员基本信息
      let member = membersList.filter((item) => {
        return item.id == value;
      });
      if(!!member&&member.length>0){
        dispatch({
          type: 'cubeReservationRecord/common',
          payload: {
            member:member[0]
          },
        });
      }else{
        dispatch({
          type: 'cubeReservationRecord/common',
          payload: {
            member:null
          },
        });
      }
      dispatch({
        type: 'cubeReservationRecord/getMemberCard',
        payload: {
          memberId:value,
          venueId:venueId
        },
      });
  }
    const options = membersList.map(d => <Option key={d.id}>{d.name}({d.phone})</Option>);
    const saveProps={
      visible,
      hideModal,
      onFinish,
      handleSearch,
      handleSelect,
      options,
      member,
      membersCardList,
      submitting,
      type,
      timeList,
      siteList,
      venueName
    }
return <Card title="预约详情" extra={<><span style={{marginRight:10}}><span style={{color:'red',fontSize:14,fontWeight:500}}>{classTableInfo.bookingNum||0}</span>/<span style={{fontSize:14,fontWeight:500}}>{classTableInfo.maximumAttendance||0}</span></span><Tooltip placement="top" title="添加预约"><AuthPlus auth={[`sign:reservation:reservation`]} onClick={()=>gotoYuyue(classTableInfo.venueId,classTableInfo.id,classTableInfo.type,classTableInfo.venueName)}/></Tooltip></>}>
            <Table columns={columns} dataSource={memberBookInfoList}/>
            <Resevation {...saveProps}/>
        </Card>
}
export default connect(({ loading, cubeReservationRecord }) => ({
    submitting: loading.effects['cubeReservationRecord/add'],
    membersList:cubeReservationRecord.membersList,
    member:cubeReservationRecord.member,
    membersCardList:cubeReservationRecord.membersCardList,
    memberBookInfoList:cubeReservationRecord.memberBookInfoList,
    shopList:cubeReservationRecord.shopList,
    coachList:cubeReservationRecord.coachList,
    timeList:cubeReservationRecord.timeList,
    siteList:cubeReservationRecord.siteList
  }))(YyRecord);